﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace CookeryBook
{
    public partial class FormIngredient : Form
    {
        OleDbConnection connec;
        int typeModif;
        
        public FormIngredient(String lineConnexion)
        {
            connec = new OleDbConnection(lineConnexion);
            typeModif = 0;
            InitializeComponent();
        }

        private void FormIngredient_Load(object sender, EventArgs e)
        {
            // Liste ingredients
            this.cmb_listeIngredient.DisplayMember = "Nom";
            this.cmb_listeIngredient.DataSource = SelectIng();

            // Mise à zéro
            cmb_unite.Items.Clear();
            // Chargement des unités dans sa liste
            for (int i = 0; i <= (int)Unite.u; i++)
            {
                cmb_unite.Items.Add((Unite)i);
            }
            cmb_unite.Refresh();

        }

        private void btn_ajouter_Click(object sender, EventArgs e)
        {
            typeModif = 1;
            MiseBlanc();
            GriseFormulaire(true);
        }

        private void btn_modifier_Click(object sender, EventArgs e)
        {
            if (cmb_listeIngredient.SelectedIndex > -1)
            {
                typeModif = 2;
                GriseFormulaire(true);
                RemplirChampsModif();
            }
            else
            {
                MessageBox.Show("Veuillez sélectionner un ingrédient");
            }
            
        }

        private void btn_supprimer_Click(object sender, EventArgs e)
        {
            if (cmb_listeIngredient.SelectedIndex > -1)
            {
                typeModif = 3;
                DeleteIng();
            }
            else
            {
                MessageBox.Show("Veuillez sélectionner un ingrédient");
            }
        }

        private void btn_ok_Click(object sender, EventArgs e)
        {
            switch (typeModif)
            {
                case 1 :
                    CreateIng();
                    break;

                case 2 :
                    ModifyIng();
                    break;

                default:
                    break;
            }

            // Remise à zéro
            typeModif = 0;
        }

        private void btn_annuler_Click(object sender, EventArgs e)
        {
            typeModif = 0;
            GriseFormulaire(false);
            MiseBlanc();
        }

        private void btn_quitter_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Fonction qui vérifie si tous les champs du formulaire "Ingredient" sont remplis
        /// </summary>
        /// <returns>Retourne vrai si tous les champs du formulaire sont remplis</returns>
        private bool VerifChamps()
        {
            return (txt_ingredient.Text.Trim() != "" && txt_description.Text.Trim() != "" && cmb_unite.Text != "");
        }

        private void RemplirChampsModif()
        {
            Ingredient ingredientSelect;
            ingredientSelect = (Ingredient)cmb_listeIngredient.SelectedItem;

            
            //Remplissage des champs
            txt_ingredient.Text = ingredientSelect.nom;
            cmb_unite.Text = Enum.GetName(typeof(Unite), ingredientSelect.unite);
            txt_description.Text = ingredientSelect.description;
        }


        private void MiseBlanc()
        {
            txt_ingredient.Text = "";
            cmb_unite.SelectedIndex = 0;
            txt_description.Text = "";
        }

        private void GriseFormulaire(bool grise)
        {
            cmb_listeIngredient.Enabled = !grise;
            txt_ingredient.Enabled = grise;
            cmb_unite.Enabled = grise;
            txt_description.Enabled = grise;
            btn_ajouter.Enabled = !grise;
            btn_modifier.Enabled = !grise;
            btn_supprimer.Enabled = !grise;
        }

        private void FinishFormulaire()
        {
            GriseFormulaire(false);
            this.cmb_listeIngredient.DataSource = SelectIng();
        }

#region Fonctions de BDD

        private List<Ingredient> SelectIng()
        {
            List<Ingredient> ingredients = new List<Ingredient>();
            OleDbDataReader reader = null;
            String description;

            try
            {
                //Commande ajout ingrédient
                connec.Open();
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = connec;
                cmd.CommandText = "Select * from ingredient";
                reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    if (reader[2] == System.DBNull.Value)
                    {
                        description = "";
                    }
                    else
                    {
                        description = reader.GetString(2);
                    }

                    ingredients.Add(new Ingredient(reader.GetInt32(0),reader.GetString(1), description,(Unite) Enum.Parse(typeof(Unite), reader.GetString(3)) ));               
                } 
            }
            catch (OleDbException ex)
            {
                System.Console.WriteLine(ex.Errors);
            }
            finally
            {
                reader.Close();
                connec.Close();
            }


            return ingredients;
        }

        private void DeleteIng()
        {
            if (DialogResult.Yes == MessageBox.Show("Voulez-vous le supprimer?","Suppression d'un ingrédient",MessageBoxButtons.YesNo))
            {
                try
                {
                    //Commande ajout ingrédient
                    connec.Open();
                    OleDbCommand cmd = new OleDbCommand();
                    cmd.Connection = connec;
                    cmd.CommandText = "Delete ingredient WHERE id = " + ((Ingredient)cmb_listeIngredient.SelectedItem).id + "";
                    cmd.ExecuteNonQuery();
                }
                catch (OleDbException ex)
                {
                    System.Console.WriteLine(ex.Errors);
                }
                finally
                {
                    connec.Close();
                    FinishFormulaire();
                }
            }
        }


        private void ModifyIng()
        {
            if (VerifChamps())
            {
                try
                {
                    //Commande ajout ingrédient
                    connec.Open();
                    OleDbCommand cmd = new OleDbCommand();
                    cmd.Connection = connec;
                    cmd.CommandText = "UPDATE ingredient SET nom = '" + txt_ingredient.Text + "', description = '" + txt_description.Text + "', unite = '" + cmb_unite.Text + "' WHERE id = " + ((Ingredient)cmb_listeIngredient.SelectedItem).id + "";
                    cmd.ExecuteNonQuery();
                }
                catch (OleDbException ex)
                {
                    System.Console.WriteLine(ex.Errors);
                }
                finally
                {
                    connec.Close();
                    FinishFormulaire();
                    MiseBlanc();
                }
            }
            else
            {
                MessageBox.Show("Veuillez remplir tous les champs !");
            }
        }


        private void CreateIng()
        {
            if (VerifChamps())
            {
                try
                {
                    //Commande ajout ingrédient
                    connec.Open();
                    OleDbCommand cmd = new OleDbCommand();
                    cmd.Connection = connec;
                    //récupération de l'id_max
                    cmd.CommandText = "SELECT MAX(id) FROM Ingredient";
                    int max_id = (int)cmd.ExecuteScalar();
                    //Incrémentation automatique de l'id adhérant
                    cmd.CommandText = "Insert into ingredient values(" + (max_id + 1) + ", '" + txt_ingredient.Text + "', '" + txt_description.Text + "', '" + cmb_unite.Text + "')";
                    cmd.ExecuteNonQuery();
                }
                catch (OleDbException ex)
                {
                    System.Console.WriteLine(ex.Errors);
                }
                finally
                {
                    connec.Close();
                    FinishFormulaire();
                    MiseBlanc();
                }
            }
            else
            {
                MessageBox.Show("Veuillez remplir tous les champs !");
            }   
            
        }

#endregion


    }
}
